<template>
  <div :class="$style.note">
    <Button type="primary" :disabled="agentIds.length<=0" @click="visible=true">发送消息</Button>
    <el-dialog :visible.sync="visible" title="发送消息" :close-on-click-modal="false" @open="beforeOpen" @opened="resetHandle">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item prop="content" label="请输入消息内容">
          <el-input v-model="formData.content" type="textarea" :autosize="{minRows:3}"></el-input>
          <p :class="$style.tip">剩余{{ 1024-formData.content.length }}字</p>
        </el-form-item>
        <el-form-item>
          <div>
            <Button @click="visible=false">取消</Button>
            <Button :loading="loading" type="primary" @click="sendHandle">发送</Button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'Note',
  components: {
  },
  props: {
    agentIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validatorLength = (r, v, c) => {
      if (v.length > 1024) {
        c(new Error('输入内容不能超过1024个字符！'))
        return
      }
      if (v.length <= 0) {
        c(new Error('请输入消息内容'))
        return
      }
      c()
    }
    return {
      visible: false,
      loading: false,
      formData: {
        content: ''
      },
      formRules: {
        content: [
          { required: true, validator: validatorLength, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    sendHandle() {
      this.loading = true
      this.$refs.form.validate().then(() => {
        return this.$cps.sendMessage(this.agentIds, this.formData.content).then(res => {
          this.visible = false
        })
      }).finally(() => {
        this.loading = false
      })
    },
    resetHandle() {
      this.$refs.form.resetFields()
    },
    beforeOpen() {
      if (this.agentIds.length <= 0) {
        this.$msgbox({
          type: 'error',
          message: '请选择坐席！',
          title: '错误'
        }).finally(() => {
          this.visible = false
        })
      }
    }
  }
}
</script>
<style lang='scss' module>
.note{
    display: inline-block;
    & .tip{
        margin: 10px 0 0 0;
        padding: 0;
        line-height: 1em;
    }
}
</style>
